﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Tools;
using System.Diagnostics;
using System.IO;
using System.Security.AccessControl;

namespace ZKInstall
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            #region 全局异常

            //处理未捕获的异常
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            //处理非UI线程异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            #endregion

            //启动目录
            SysConstant.AppStartPath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);

            #region 日志文件夹

            LogHelper.LogPath = SysConstant.AppStartPath + @"\Log\";
            LogHelper.LogPath = LogHelper.LogPath.Replace("/", "\\");

            IOHelper.CreateFolder(LogHelper.LogPath);

            IOHelper.DeleteFiles(LogHelper.LogPath, new string[] { ".txt", ".log" }, 4);//删除4天前日志文件
            #endregion

            //int mainVer = (new WebBrowser()).Version.Major;

            #region 启动入口
#if DEBUG
            SysConstant.MainForm = new MainForm();
            SysConstant.CurrForm = SysConstant.MainForm;
            Application.Run(SysConstant.MainForm);
#else
            run(args);
#endif

            #endregion

            NotifyIconHelper.NotifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(TaskBarLeftDown_Click);
        }

        /// <summary>
        /// 运行
        /// </summary>
        private static void run(string[] args)
        {
            String runArg = "run";//运行参数
            if (args.Length == 0 || !args[0].Trim().Equals(runArg))
            {
                MessageBox.Show("缺少运行参数，请使用 run.bat 启动！");
                Application.Exit();
                return;
            }

            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();//获得当前登录的Windows用户标示
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);

            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))//判断当前登录用户是否为管理员
            {
                SysConstant.MainForm = new MainForm();
                SysConstant.CurrForm = SysConstant.MainForm;
                Application.Run(SysConstant.MainForm);
            }
            else
            {
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                startInfo.Arguments = runArg;
                startInfo.UseShellExecute = true;
                startInfo.WorkingDirectory = Environment.CurrentDirectory;
                startInfo.FileName = Application.ExecutablePath;
                startInfo.Verb = "runas";//设置启动动作,确保以管理员身份运行
                try
                {
                    System.Diagnostics.Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                //退出
                Application.Exit();
            }
        }

        #region 托盘相关

        /// <summary>
        /// 任务栏单击击图标
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void TaskBarLeftDown_Click(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                SysConstant.CurrForm.Show();
                if (SysConstant.CurrForm.WindowState == FormWindowState.Minimized)
                {
                    SysConstant.CurrForm.WindowState = FormWindowState.Normal;
                }
                SysConstant.CurrForm.Activate();
            }
        }
        #endregion

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = "";
            string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
            Exception error = e.Exception as Exception;
            if (error != null)
            {
                str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                error.GetType().Name, error.Message, error.StackTrace);
            }
            else
            {
                str = string.Format("应用程序线程错误:{0}", e);
            }

            LogHelper.SaveErrorLog("出现应用程序未处理的异常", str);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = "";
            Exception error = e.ExceptionObject as Exception;
            string strDateInfo = "出现应用程序未处理的异常：" + DateTime.Now.ToString() + "\r\n";
            if (error != null)
            {
                str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆栈信息:{1}", error.Message, error.StackTrace);
            }
            else
            {
                str = string.Format("Application UnhandledError:{0}", e);
            }

            //MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            LogHelper.SaveErrorLog("出现应用程序未处理的异常", str);
        }
    }
}
